<?php
namespace frontend\controllers;

use common\components\FrontBaseController;
use frontend\models\HryOrder;
use Yii;
use \common\helps\tools;
use common\helps\detection;
use \common\helps\code;
use yii\db\Query;

/**
 * User controller
 */
class GroupController extends FrontBaseController
{

    public $modelClass = 'frontend\models\Group';
    public function init()
    {
        parent::init();
    }

    /*
     * 群组分类社群列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGroupCatIndex()
    {
        $model = new \frontend\models\GroupCat();
        $request =$this->request;
        $params = $request->queryParams;
        //$member_info = $this->member_info;

        $res = $model::selectFieldData([],'`id`,`name`');
        //$res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 热门群组
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionHotGroup(){
        $model = new \frontend\models\Group();
        $posts = new \frontend\models\Posts();
        $comment = new \frontend\models\Comment();
        $request =$this->request;
        $params = $request->bodyParams;
        $memberInfo = tools::getMemberInfoByToken();
        $member_id = empty($memberInfo['id'])?'':$memberInfo['id'];

        $data = $model::selectLimitInfo(['member_id' => $member_id],'`id`,`name`,`describe`,`cover`',0,10);
        foreach ($data as $k => $v){
            //$data[$k]['group_num'] = count($group::selectFieldData(['group_id' => $v['id']],'id'));
            $data[$k]['posts'] = $posts::selectData(['group_id' => $v['id'],'limit' => 2],'`posts`.`id`,`posts`.`title`');
            foreach ($data[$k]['posts'] as $key => $val){
                $row = $comment::findAllData(['posts_id' => $val['id']],'`m`.`head_img`,`member_id`','member_id');
                $data[$k]['posts'][$key]['talk_num'] = count($row);
                $data[$k]['posts'][$key]['comment_img'] = $row;
            }
        }
        $res = tools::getPageData($data,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
//        $timeKey =  array_column( $data, 'group_num'); //取出数组中status的一列，返回一维数组
//        array_multisort($timeKey, SORT_DESC, $data);
    }

    /*
     * 热门讨论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionHotPosts()
    {
        $model = new \frontend\models\Posts();
        $comment = new \frontend\models\Comment();
        $memberInfo = tools::getMemberInfoByToken();
        $member_id = empty($memberInfo['id'])?'':$memberInfo['id'];

        $res = $model::selectData(['limit' => 3,'for_group' => 1,'auth' => 1,'member_id' => $member_id,'get_group' => 1],'`posts`.`id`,`posts`.`title`');
        foreach ($res as $k => $v){
            $row = $comment::findAllData(['posts_id' => $v['id']],'`m`.`head_img`,`member_id`','member_id');
            $res[$k]['talk_num'] = count($row);
            $res[$k]['comment_img'] = $row;
        }
        return code::success($res);
    }

    /*
     * 群组列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGroupList(){
        $model = new \frontend\models\Group();
        $posts = new \frontend\models\Posts();
        $comment = new \frontend\models\Comment();
        $request =$this->request;
        $params = $request->bodyParams;
        $memberInfo = tools::getMemberInfoByToken();
        $params['member_id'] = $memberInfo['id'];

        $data = $model::selectLimitInfo($params,'`id`,`name`,`describe`,`cover`');
        foreach ($data as $k => $v){
            $data[$k]['posts'] = $posts::selectData(['group_id' => $v['id'],'limit' => 2],'`posts`.`id`,`posts`.`title`');
            foreach ($data[$k]['posts'] as $key => $val){
                $row = $comment::findAllData(['posts_id' => $val['id']],'`m`.`head_img`,`member_id`','member_id');
                $data[$k]['posts'][$key]['talk_num'] = count($row);
                $data[$k]['posts'][$key]['comment_img'] = $row;
            }
        }
        $res = tools::getPageData($data,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 群组详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGroupDetail(){
        $model = new \frontend\models\Group();
        $request =$this->request;
        $params = $request->bodyParams;
        $memberInfo = tools::getMemberInfoByToken();
        $member_id = empty($memberInfo['id'])?'':$memberInfo['id'];

        $res = $model::findInfo(['id' => $params['id'],'member_id' => $member_id],'`id`,`name`,`describe`,`cover`,`background_img`');
        return code::success($res);
    }

    /*
     * 我的群组
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionMyGroup(){
        $model = new \frontend\models\Group();
        $member_info = $this->member_info;

        $data = $model::selectJoinInfo(['member_id' => $member_info['id']],'`group`.`id`,`name`,`describe`,`cover`');
        $res = tools::getPageData($data,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 加入群组
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddGroup(){
        $model = new \frontend\models\Group();
        $order = new \frontend\models\TfOrder();
        $gmember = new \frontend\models\GroupMember();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $res = $model::findOne(['id' => $params['id']]);
        if(empty($res)){
            return code::error('mistake');
        }
        $res = $res->toArray();
        if(!empty($res['experience']) && $member_info['experience'] <= $res['experience']){
            return code::error('','经验值不足'.$res['experience'].'，无法加入');
        }
        if(!empty($res['project_id'])){   // 此处的判断使用db2直接链接好融艺查询
//            $tfOrder = $order::findInfo(['uid' => $member_info['id'],'project_id' => $res['project_id']],'id');
              $hryModel =new HryOrder();
            if(empty($this->member_info['hry_member_id'])){
                return code::error('','只有投过该项目的才可以加入该群组');
            }
              $tfOrder = $hryModel->getHryMemberOrder(intval($res['project_id']),intval($this->member_info['hry_member_id']));
            if(empty($tfOrder['id'])){
                return code::error('','只有投过该项目的才可以加入该群组');
            }
        }
        $row = $gmember::findOne(['member_id' => $member_info['id'],'group_id' => $res['id']]);
        if(empty($row['id'])){
            $rat = $gmember::addData(['member_id' => $member_info['id'],'group_id' => $res['id']]);
            if(empty($rat->errorInfo)){
                return code::success($rat);
            }else{
                return code::error('error');
            }
        }else{
            return code::error('','您已加入过该群组');
        }
    }

    /*
     * 退出群组
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionQuitGroup(){
        $model = new \frontend\models\GroupMember();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $data = [
            'group_id' => $params['id'],
            'member_id' => $member_info['id']
        ];
        $res = $model::quitGroup($data);
        if($res){
            return code::success($res);
        }else{
            return code::error('error');
        }
    }

    /*
     * 发帖
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddPosts()
    {
        $model = new \frontend\models\Posts();
        $pjoin = new \frontend\models\PostsJoin();
        $member_info = $this->member_info;
        $request = $this->request;
        $params = $request->bodyParams;
        if ($model->load($params, '')) {
            if ($model->validate()) {
                if(empty($params['group_id'])){
                    return code::error('mistake');
                }
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $params['set_posts_id'] = $member_info['id'];
                    $params['set_posts_name'] = $member_info['username'];
//                    $movie_id = $params['movie_id'];
//                    unset($params['movie_id']);
                    $params['title'] = trim($params['title']);
                    $params['describe'] = trim($params['describe']);
                    $params['type'] = 2;
                    if(empty($params['describe'])){
                        return code::error('','请输入有效内容');
                    }
                    $res = $model->saveInfo('create', $params);
                    $data['posts_id'] = $res;
                    $data['group_id'] = $params['group_id'];
//                    $data['item_id'] = !empty($params['item_id'])?$params['item_id']:'';
//                    $data['movie_id'] = !empty($movie_id)?$movie_id:'';
                    $rat = $pjoin->saveInfo('create',$data);
                    if (empty($res->errorInfo) && empty($rat->errorInfo)) {
                        $transaction->commit();
                        return code::success(true);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                    throw new Exception($e->getMessage());
                }
            } else {
                $error = array_values($model->getErrors());
                return code::error('', $error[0][0]);
            }
        }
    }

    /*
     * 评论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddComment()
    {
        $model = new \frontend\models\Comment();
        $posts = new \frontend\models\Posts();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $data = [
            'posts_id' => $params['posts_id'],
            'comment' => trim($params['comment']),
            'member_id' => $member_info['id'],
            'member_name' => $member_info['username'],
        ];
        if(empty($data['comment'])){
            return code::error('','评论内容不能为空');
        }
        //文本检测敏感词
        $detection = new detection();
        $check_res=$detection->checkWord($data['comment']);
        if($check_res['errcode']!=0){
            return code::error('error','评论内容含有敏感词汇');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $res = $model::addData($data);
            $row = $posts::addNum($params['posts_id']);
            if ($res && $row) {
                $transaction->commit();
                return code::success(true);
            }
        } catch (\Exception $e) {
            $error = $e->getMessage();
            $transaction->rollBack();
        }
        return code::error('error');
    }


}
